package com.zd.ticketing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.zd.common.bean.model.TicketInfo;
import com.zd.common.bean.model.TicketOrder;
import com.zd.common.bean.model.TicketOrderDetail;
import com.zd.common.bean.model.UserIdInfo;
import com.zd.common.bean.model.UserInfo;
import com.zd.common.bean.model.UserReceiveInfo;
import com.zd.common.common.constant.CommonConstant;
import com.zd.common.common.enums.PayStatusEnum;
import com.zd.common.common.utils.DateTimeUtil;
import com.zd.common.common.utils.JSONUtil;
import com.zd.common.common.utils.LogUtils;
import com.zd.common.dao.TicketInfoDao;
import com.zd.common.dao.TicketOrderDao;
import com.zd.common.dao.TicketOrderDetailDao;
import com.zd.common.dao.UserIdInfoDao;
import com.zd.common.dao.UserInfoDao;
import com.zd.common.dao.UserReceiveInfoDao;
import com.zd.common.dao.common.BaseDao;
import com.zd.common.dao.common.FindRequestEntity;
import com.zd.common.dao.common.OrderEnum;
import com.zd.common.dao.common.WhereEnum;
import com.zd.common.service.impl.BaseServiceImpl;
import com.zd.ticketing.bean.vo.TicketOrderVo;
import com.zd.ticketing.service.IUserInfoService;

/**
 * @author lishi
 * @date 2018年11月8日 上午9:26:15
 */
@Service
public class UserInfoServiceImpl extends BaseServiceImpl<UserInfo> implements IUserInfoService {
	
	@Autowired
	private UserInfoDao userInfoDao;
	
	@Autowired
	private UserReceiveInfoDao userReceiveInfoDao;
	
	@Autowired
	private TicketOrderDetailDao ticketOrderDetailDao;
	
	@Autowired
	private UserIdInfoDao userIdInfoDao;
	
	@Autowired
	private TicketInfoDao ticketInfoDao;
	
	@Autowired
	private TicketOrderDao ticketOrderDao;

	@Override
	public BaseDao<UserInfo> getBaseDao() {
		return userInfoDao;
	}

	@Override
	public UserInfo findOpenId(Integer scenicSpotId, String openid,String nickname ,String img) throws Exception {
		FindRequestEntity findReq = new FindRequestEntity();
		findReq.addWhere("openid", WhereEnum.EQ, openid);
		findReq.addWhere("scenic_spot_id", WhereEnum.EQ, scenicSpotId);
		List<UserInfo> userInfoList = userInfoDao.find(findReq);
		if(userInfoList != null &&  userInfoList.size() > 0){
			return userInfoList.get(0);
		}else {
			UserInfo userInfo = new UserInfo();
			userInfo.setScenicSpotId(scenicSpotId);
			userInfo.setOpenid(openid);
			userInfo.setImg(img);
			userInfo.setNickname(nickname);
			userInfo.setCreateTime(new Date());
			userInfo.setUpdateTime(new Date());
			userInfoDao.insert(userInfo);
			return userInfo;
		}
	}

	@Override
	public Map<String, Object> findUserInformation(Integer userId) throws Exception {
		FindRequestEntity findReq = new FindRequestEntity();
		findReq.addWhere("user_info_id", WhereEnum.EQ, userId);
		List<UserIdInfo> userIdInfoList = userIdInfoDao.find(findReq);
		List<UserReceiveInfo> userReceiveInfoList = userReceiveInfoDao.find(findReq);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("userIdInfoList", userIdInfoList);
		resultMap.put("userReceiveInfoList", userReceiveInfoList);
		return resultMap;
	}

	@Override
	public Map<String, Object> analysisTouristJson(String touristJson,boolean updateType) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		LogUtils.debug(touristJson);
		JSONObject jsonTicke = JSONUtil.getJSONFromString(touristJson);
		String userReceiveInfoVal = jsonTicke.getString("userReceiveInfoVal");
		String userIdInfos =  jsonTicke.getString("userIdInfoList");
		String payAccountId = jsonTicke.getString("payAccountId");
		String userId =  jsonTicke.getString("userId");
		String ticketInfoId =  jsonTicke.getString("ticketInfoId");
		String ticketInfoNum =  jsonTicke.getString("ticketInfoNum");
		String entryTime =  jsonTicke.getString("entryTime");
		String appId = jsonTicke.getString("appId");
		
		TicketInfo ticketInfo = ticketInfoDao.get(Integer.valueOf(ticketInfoId));
		
		List<UserIdInfo> userIdInfoList = JSONUtil.jsonToList(userIdInfos, UserIdInfo.class);
		
		
		UserReceiveInfo userReceiveInfo = JSONUtil.toBean(userReceiveInfoVal, UserReceiveInfo.class);
		
		resultMap.put("appId", appId);
		resultMap.put("tatolPrices", userIdInfoList.size() * ticketInfo.getPrice());
		resultMap.put("userId", userId);
		resultMap.put("payAccountId", payAccountId);
		resultMap.put("ticketInfo", ticketInfo);
		resultMap.put("ticketInfoNum", ticketInfoNum);
		resultMap.put("entryTime", entryTime);
		resultMap.put("userIdInfoList", userIdInfoList);
		resultMap.put("userReceiveInfo", userReceiveInfo);
		if(updateType){
			saveOrUpdateUserIdInfInformation(userIdInfoList, Integer.valueOf(userId));
			saveOrUpdateUserReceiveInformation(userReceiveInfo, Integer.valueOf(userId));
		}
		return resultMap;
	}

	@Override
	public Map<String, String> saveOrUpdateUserReceiveInformation(UserReceiveInfo userReceiv, Integer userId) throws Exception {
		Map<String, String> resultMap = new HashMap<>();
		FindRequestEntity findReq = new FindRequestEntity();
		findReq.addWhere("user_info_id", WhereEnum.EQ, userId);
		findReq.addWhere("name", WhereEnum.EQ, userReceiv.getName());
		List<UserReceiveInfo> userReceiveInfoList = userReceiveInfoDao.find(findReq);
		if(userReceiveInfoList != null && userReceiveInfoList.size() > 0){
			UserReceiveInfo userReceiveInfo = userReceiveInfoList.get(0);
			userReceiveInfo.setPhone(userReceiv.getPhone());
			userReceiveInfo.setCarNo(userReceiv.getCarNo());
			userReceiveInfo.setIdNumber(userReceiv.getIdNumber());
			userReceiveInfo.setUpdateTime(new Date());
			userReceiveInfoDao.update(userReceiveInfo);
			resultMap.put("SUCCESS", "修改成功");
		}else {
			userReceiv.setUserInfoId(userId);
			userReceiv.setCreateTime(new Date());
			userReceiv.setUpdateTime(new Date());
			userReceiveInfoDao.insert(userReceiv);
			resultMap.put("SUCCESS", "保存成功");
		}
		return resultMap;
	}

	@Override
	public Map<String, String> saveOrUpdateUserIdInfInformation(List<UserIdInfo> userIdInfoList, Integer userId) throws Exception {
		Map<String, String> resultMap = new HashMap<>();
		for (UserIdInfo userIdInfo : userIdInfoList) {
			FindRequestEntity findReq = new FindRequestEntity();
			findReq.addWhere("user_info_id", WhereEnum.EQ, userId);
			findReq.addWhere("user_name", WhereEnum.EQ, userIdInfo.getUserName());
			List<UserIdInfo> userIdInfos = userIdInfoDao.find(findReq);
			if(userIdInfos != null && userIdInfos.size() > 0){
				UserIdInfo uIdInfo = userIdInfos.get(0);
				uIdInfo.setPhone(userIdInfo.getPhone());
				uIdInfo.setIdType(userIdInfo.getIdType());
				uIdInfo.setIdNumber(userIdInfo.getIdNumber());
				uIdInfo.setUpdateTime(new Date());
				userIdInfoDao.update(uIdInfo);
			}else {
				userIdInfo.setUserInfoId(userId);
				userIdInfo.setCreateTime(new Date());
				userIdInfo.setUpdateTime(new Date());
				userIdInfoDao.insert(userIdInfo);
			}
		}
		resultMap.put("SUCCESS", "修改保存成功");
		return resultMap;
	}

	@Override
	public Map<String, Object> findUserOrder(Integer userId) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		FindRequestEntity findReq = new FindRequestEntity();
		findReq.addWhere("user_id", WhereEnum.EQ, userId);
		findReq.addWhere("status", WhereEnum.EQ, PayStatusEnum.To_be_paid.getKey());
		findReq.addOrder("create_time",OrderEnum.DESC );
		List<TicketOrder> ticketOrderToBePaidList = ticketOrderDao.find(findReq);
		List<TicketOrderVo> ticketOrderVoToBePaidList = getTicketOrderVoList(ticketOrderToBePaidList);
		resultMap.put("ToBePaidNum", ticketOrderVoToBePaidList.size());
		resultMap.put("ToBePaid", ticketOrderVoToBePaidList);
		
		findReq = new FindRequestEntity();
		findReq.addWhere("user_id", WhereEnum.EQ, userId);
		findReq.addWhere("status", WhereEnum.EQ, PayStatusEnum.Payment_success.getKey());
		findReq.addOrder("create_time",OrderEnum.DESC );
		findReq.setPage(1, CommonConstant.DEFAULT_PAGE_SZIE);
		List<TicketOrder> ticketOrderPaymentSuccessList = ticketOrderDao.find(findReq);
		List<TicketOrderVo> ticketOrderVoPaymentSuccessList = getTicketOrderVoList(ticketOrderPaymentSuccessList);
	
		resultMap.put("PaymentSuccess", ticketOrderVoPaymentSuccessList);
		
		return resultMap;
	}
	
	/**
	 * 将TicketOrder实体集合转为页面需要的TicketOrderVo集合
	 * @param ticketOrderList
	 * @return
	 * @throws Exception
	 */
	private List<TicketOrderVo> getTicketOrderVoList(List<TicketOrder> ticketOrderList)throws Exception{
		List<TicketOrderVo> ticketOrderVoList = new ArrayList<>();
		for (TicketOrder ticketOrder : ticketOrderList) {
			TicketOrderVo ticketOrderVo = new TicketOrderVo();
			BeanUtils.copyProperties(ticketOrder, ticketOrderVo);
			TicketInfo ticketInfo = ticketInfoDao.get(ticketOrder.getTicketId());
			ticketOrderVo.setTickectName(ticketInfo.getName());
			ticketOrderVo.setTickectImage(ticketInfo.getThumbImg());
			ticketOrderVo.setOrderTime(DateTimeUtil.date2String(ticketOrder.getCreateTime()));
			
			FindRequestEntity findReq = new FindRequestEntity();
			findReq.addWhere("order_id", WhereEnum.EQ, ticketOrder.getId());
			List<TicketOrderDetail> ticketOrderDetails = ticketOrderDetailDao.find(findReq);
			if(ticketOrderDetails != null && ticketOrderDetails.size() > 0){
				ticketOrderVo.setValidTime(DateTimeUtil.date2String(ticketOrderDetails.get(0).getValidTime()));
			}
			ticketOrderVoList.add(ticketOrderVo);
		}
		return ticketOrderVoList;
	}

	@Override
	public void savePayOpenId(String payOpenId, Integer userId) throws Exception {
		UserInfo userInfo = userInfoDao.get(userId);
		if(userInfo.getPayOpenid() == null){
			userInfo.setPayOpenid(payOpenId);
			userInfo.setUpdateTime(new Date());
			userInfoDao.update(userInfo);
		}
	}

	@Override
	public List<TicketOrderVo> pageTicketOrder(Integer page, Integer userId) throws Exception {
		FindRequestEntity findReq = new FindRequestEntity();
		if (page == null || page == 0) {
            page = 1;
        }
		findReq.setPage(page, CommonConstant.DEFAULT_PAGE_SZIE);
		findReq.addWhere("user_id", WhereEnum.EQ, userId);
		findReq.addWhere("status", WhereEnum.EQ, PayStatusEnum.Payment_success.getKey());
		findReq.addOrder("create_time", OrderEnum.DESC);
		List<TicketOrder> ticketOrderList = ticketOrderDao.find(findReq);
		return getTicketOrderVoList(ticketOrderList);
	}


}
